package com.woniu.project.filter.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Klaus
 * @Date: 2020/9/22 18:56
 */
//网关的全局异常处理
@Component
@Order(-1)
public class GlobleExceptionHandler implements ErrorWebExceptionHandler {

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
        System.out.println("进入网关异常处理");
        Map<String,Object> error = new HashMap<>();
        error.put( "code", 500);
        error. put("msg",throwable.getMessage());
        throwable.printStackTrace();
//        error.put( "error", throwable);

        //设置相应头
        serverWebExchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //响应一些数据回去
        return serverWebExchange.getResponse().writeWith(Mono.fromSupplier(() -> {
            try {
                return serverWebExchange.getResponse().bufferFactory().wrap(objectMapper.writeValueAsBytes(error));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return null;
            }
        }));

    }
}
